package cn.genmer.test.security.recordlog.handler;

import cn.genmer.test.security.mapper.ModificationLogMapper;
import cn.genmer.test.security.model.po.ModificationLogPO;
import cn.genmer.test.security.recordlog.jdbc.QueryWrapper;
import cn.genmer.test.security.recordlog.reflect.DiffPropertyDefinition;
import cn.genmer.test.security.recordlog.reflect.Source;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * @description: 修改日志结果保存
 * @author: yyq
 * @date: 2023/8/28 10:46
 */

@Component
@Slf4j
public class BusLogDiffHandler implements LogDiffHandler {

    @Autowired
    private ModificationLogMapper modificationLogMapper;

    @Override
    public void handler(QueryWrapper queryWrapper, List<DiffPropertyDefinition> diffPropertyList) {
        for (DiffPropertyDefinition diffPropertyDefinition : diffPropertyList) {
            ModificationLogPO logPO = new ModificationLogPO();
            logPO.setCreatedBy(queryWrapper.getModifiedBy());
            logPO.setCreatedTime(new Date());
            logPO.setTableName(queryWrapper.getTable().toUpperCase(Locale.ROOT));
            logPO.setBusPrimaryKey(queryWrapper.getPrimaryParam().getValue().toString());
            logPO.setField(diffPropertyDefinition.getFieldMetadata().getName());
            logPO.setFieldName(diffPropertyDefinition.getFieldMetadata().getDesc());
            logPO.setOriginalValue(diffPropertyDefinition.getOldValue().toString());
            logPO.setOriginalValue(diffPropertyDefinition.getOldValue() != null ? diffPropertyDefinition.getOldValue().toString() : "");
            logPO.setModifiedValue(diffPropertyDefinition.getNewValue() != null ? diffPropertyDefinition.getNewValue().toString() : "");
            Source modifiedSource = queryWrapper.getModifiedSource();
            if (modifiedSource != null) {
                logPO.setModifiedSource(modifiedSource.getSource());
                logPO.setOperationSequenceNumber(modifiedSource.getOptSequenceNumber());
            }
            modificationLogMapper.insert(logPO);
        }
    }
}
